package com.lyz.dataStructure.LeetCode.ListNode;

/**
 *@Author:759057893@qq.com Lyz
 *@Date: 2019/7/19 20:09
 *@Description:
 **/

/*
每隔K步进行反转
 */
public class ReverseKListNode {
    public static void main(String[] args) {
        ListNode node = createListNode();
        System.out.println(node);

        System.out.println(reverseKGroup(node,4));
    }

    public static  ListNode createListNode(){
        ListNode listNode = new ListNode(0);
        ListNode curr = listNode;
        for(int i=1;i<8;i++){
            curr.next = new ListNode(i);
            curr = curr.next;
        }
        return listNode;
    }


    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode pre = dummy;
        ListNode end = dummy;

        while (end.next != null) {
            for (int i = 0; i < k && end != null; i++)
            {
                end = end.next;
            }
            if (end == null) break;
            ListNode start = pre.next;
            ListNode next = end.next;
            end.next = null;
            pre.next = reverse(start);
            start.next = next;
            pre = start;

            end = pre;
        }
        return dummy.next;
    }

    private static ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }
}
